package com.zzw.springboot.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzw.springboot.entity.Menu;
import com.zzw.springboot.mapper.MenuMapper;
import com.zzw.springboot.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzw
 * @since 2022-05-28 20:32:01
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public List<Menu> findMenus(String name) {
        // 查询所有数据
        List<Menu> list = list(Wrappers.<Menu>lambdaQuery()
                .like(StringUtils.isNotEmpty(name), Menu::getName, name)
                .orderByDesc(Menu::getSortNum));
        // 找出pid为null的一级菜单
        List<Menu> parentNodes = list.stream()
                .filter(menu -> menu.getPid() == null)
                .collect(Collectors.toList());
        // 找出一级菜单的子菜单
        for (Menu menu : parentNodes) {
            // 筛选所有数据中pid=父级id的数据就是二级菜单
            menu.setChildren(list.stream()
                    .filter(m -> menu.getId().equals(m.getPid()))
                    .collect(Collectors.toList()));
        }
        return parentNodes;
    }
}
